package com.agrimall.servlet.client;

import com.agrimall.util.AIUtil;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * AI咨询Servlet
 * 处理客户端AI咨询请求
 */
@WebServlet("/client/ai/consultation")
public class AIConsultationServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    
    // 快捷问题列表
    private static final List<String> QUICK_QUESTIONS = Arrays.asList(
        "如何选择新鲜的蔬菜？",
        "水果的保存方法有哪些？",
        "有机农产品和普通农产品有什么区别？",
        "如何判断鸡蛋是否新鲜？",
        "茶叶的冲泡方法有哪些？",
        "粮食的储存注意事项？",
        "如何挑选优质的农产品？",
        "农产品的营养价值如何？",
        "如何识别农药残留？",
        "农产品的最佳食用时间是什么时候？",
        "如何保存蔬菜的新鲜度？",
        "水果的成熟度如何判断？",
        "有机认证的标准是什么？",
        "如何正确清洗农产品？",
        "农产品的季节性特点是什么？"
    );
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("quickQuestions".equals(action)) {
            // 获取随机快捷问题
            getQuickQuestions(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("ask".equals(action)) {
            // 处理AI咨询请求
            askQuestion(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 获取随机快捷问题
     */
    private void getQuickQuestions(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 随机选择3-5个问题
            List<String> questions = new ArrayList<>(QUICK_QUESTIONS);
            Collections.shuffle(questions);
            int count = 3 + new Random().nextInt(3); // 3-5个
            count = Math.min(count, questions.size());
            List<String> selectedQuestions = questions.subList(0, count);
            
            result.put("success", true);
            result.put("questions", selectedQuestions);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取快捷问题失败：" + e.getMessage());
        }
        
        out.print(objectMapper.writeValueAsString(result));
    }
    
    /**
     * 处理AI咨询请求
     */
    private void askQuestion(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            request.setCharacterEncoding("UTF-8");
            String question = request.getParameter("question");
            
            if (question == null || question.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "问题不能为空");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            // 调用AI工具类
            String answer = AIUtil.askQuestion(question);
            
            result.put("success", true);
            result.put("answer", answer);
            result.put("question", question);
        } catch (NoApiKeyException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "AI服务配置错误：API Key未配置");
        } catch (ApiException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "AI服务调用失败：" + e.getMessage());
        } catch (InputRequiredException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "输入参数错误：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        out.print(objectMapper.writeValueAsString(result));
    }
}


